package com.bootdo.clouddo.controller.douban;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.utils.R;
import com.bootdo.clouddo.utils.StringUtils;

@RestController
@RequestMapping("/fm/douban")
public class FmController {

	public static final String app_channels_url = "https://api.douban.com/v2/fm/app_channels?app_name=radio_android&apikey=02f7751a55066bcb08e65f4eff134361&user_accept_play_third_party=1&version=651&audio_patch_version=4";
	
	public static final String play_list_url = "https://api.douban.com/v2/fm/playlist?apikey=02f7751a55066bcb08e65f4eff134361&max=30&type=n&version=651&audio_patch_version=4&app_name=radio_android&user_accept_play_third_party=1&client=s:mobile|v:4.6.11|y:android 5.1.1|f:651|m:OPPO|d:7e91aa3bc63255a67f8907ec0e6a381c726fb34d|e:oneplus_one_e1001";
	
	public static final String token_url = "https://www.douban.com/service/auth2/token";

	public static final String lyric_url = "https://fm.douban.com/j/v2/lyric";
	
	@GetMapping("/channels")
	public R getAppChannels(String token) {
		try {
			JSONObject resultVo = sendGetRequest(app_channels_url, token);
			if(resultVo != null) {
				return R.data(resultVo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error();
	}
	
	@GetMapping("/playlist/{channel}")
	public R getPlayList(@PathVariable String channel, String token) {
		try {
			JSONObject resultVo = sendGetRequest(play_list_url + "&channel=" + channel, token);
			if(resultVo != null) {
				return R.data(resultVo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error();
	}
	
	@GetMapping("/getToken")
	public R getToken(String username, String password) {
		try {
			MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
		    map.add("email", "first.last@example.com");
			map.add("username", username);
			map.add("password", password);
			map.add("client_id", "02f7751a55066bcb08e65f4eff134361");
			map.add("client_secret", "63cf04ebd7b0ff3b");
			map.add("redirect_uri", "http://douban.fm");
			map.add("grant_type", "password");
			JSONObject resultVo = sendPostFormRequest(token_url, map);
			if(resultVo != null) {
				return R.data(resultVo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error();
	}

	@GetMapping("/lyric")
	public R lyric(String sid, String ssid) {
		try {
			JSONObject resultVo = sendGetRequest(lyric_url + "?sid=" + sid + "&ssid=" + ssid);
			if(resultVo != null) {
				return R.data(resultVo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error();
	}
	
	public static JSONObject getRequest(String url, Map<String, String> params){
    	SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    	requestFactory.setConnectTimeout(3000);// 设置超时
    	requestFactory.setReadTimeout(3000);
        RestTemplate client = new RestTemplate(requestFactory);
        return client.getForObject(url, JSONObject.class,  params);
    }
	
	public static JSONObject sendGetRequest(String url) {
		return sendGetRequest(url, new HashMap<>());
	}
	
	public static JSONObject sendGetRequest(String url, String token) {
		return sendGetRequest(url, new HashMap<>(), token);
	}
	
	public static JSONObject sendGetRequest(String url, Map<String, String> params) {
		return sendGetRequest(url, params, null);
	}
	
	public static JSONObject sendGetRequest(String url, Map<String, String> params, String token){
        RestTemplate client = new RestTemplate();
        HttpMethod method = HttpMethod.GET;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        if(StringUtils.isNotBlank(token)) {
        	headers.add("Authorization", "Bearer "+token);
        }
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers);
        
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<JSONObject> response = client.exchange(url, method, requestEntity, JSONObject.class);

        return response.getBody();
    }
	
	public static JSONObject sendPostRequest(String url, Map<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpMethod method = HttpMethod.POST;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers);
        
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<JSONObject> response = client.exchange(url, method, requestEntity, JSONObject.class);

        return response.getBody();
    }
	
	public static JSONObject sendPostFormRequest(String url, MultiValueMap<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpMethod method = HttpMethod.POST;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<JSONObject> response = client.exchange(url, method, requestEntity, JSONObject.class);

        return response.getBody();
    }
}
